<?php

namespace App\Http\Controllers\home;
use App\HouseUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\House;
use App\User;
use App\Admin;

class HouseController extends Controller
{

    // 把软删除记录恢复为普通记录;
    public function restore(){
        House::withTrashed()->restore();
    }

    // 房源上架 | 下架
    public function state(Request $request){
        
        $house = House::find($request->id);
        $house->state = $request->state;
        $bool = $house->save();
        
        if($bool){
            $msg = $request->state ? '上架成功!':'下架成功!';
            return response()->json(['status'=>200,'msg'=>$msg]);
        }else{
            $msg = $request->state ? '上架失败!':'下架失败!';
            return response()->json(['status'=>3000,'msg'=>'状态更新失败!']);
        }

    }

     // 删除图片 
    public function delimg(Request $request){

      //return  $_SERVER["DOCUMENT_ROOT"];

      $house = House::find($request->id);
      $imgArr = explode("&",$house->imgs);
      $picName = $imgArr[$request->index];

      $file = $_SERVER["DOCUMENT_ROOT"].'/upload/'.$picName;
      

      // 删除文件 
      if(file_exists($file)){
          unlink($file);
      }

      // 数据库删除;
      array_splice($imgArr, $request->index, 1);
      $house->imgs = implode('&',$imgArr);
      $bool = $house->save();

        // 返回数据
        if($bool){
            return response()->json(['msg'=>'删除成功!','code'=>'200']);
        }else{
            return response()->json(['msg'=>'删除失败!','code'=>'3000']);
        }


    }

    // 房屋上架
    public function sale(Request $request){

        $house = House::find($request->id);
        $house->state = $request->state =="true"  ? 1:0;
        $bool = $house->save();
        
        if($bool){
             $msg = $house->state == 1 ? "房源上架成功!" : "房源下架成功!";
            return response()->json(['meta'=>['status'=>200,'msg'=>$msg]]);
        }else{
            $msg = $house->state == 1 ? "房源上架失败!" : "房源下架失败!";
            return response()->json(['meta'=>['status'=>200,'msg'=>$msg]]);
        }
        
    }
    
    // 房屋删除 
    public function del(Request $request){

       $res =  House::find($request->id)->delete();
       
       if($res){
          return response()->json(['meta'=>['status'=>200,'msg'=>'房源删除成功!']]);
       }else{
          return response()->json(['meta'=>['status'=>3000,'msg'=>'房源删除失败!']]);
       }
       
    }
    
    // 关注房屋
    public function like(Request $request){ 
        
        $user = \Auth::guard('wechat')->user();
        $user->liked_houses()->attach($request->id);
        return response()->json(["msg"=>"关注成功","status"=>"201"]);
        
    }
     
    // 取消关注房屋
    public function unlike(Request $request){
        $user = \Auth::guard('wechat')->user();
        $user->liked_houses()->detach($request->id);
        return response()->json(["msg"=>"取消关注成功","status"=>"201"]);
    }
    
    //搜索房屋
    public function  search(Request $request){
        $words = $request->words;
        $houses = House::where("title","like","%".$words."%")->paginate(6);
        foreach($houses as $k=>$house){
            $houses[$k]["coverurl"]= $this->getCoverImg($house["imgs"]);
            unset($houses[$k]["imgs"]);
            unset($houses[$k]["openid"]);
        }
        return $houses;
    }

    // 是否关注
    private function  liked($uid,$id){

        return (bool) HouseUser::where("user_id","=",$uid)
                 ->where("house_id","=",$id)
                 ->first();

    }


    // 获取房屋详情 
    public function detail(Request $request){

        $token = $request->bearerToken()?$request->bearerToken():$request->token;
        $house = House::find($request->id);

        if(strlen($house->imgs)>6){
            $house->imgs = $this->getImgArr($house->imgs);
        }else{
            $house->imgs = Array();
        }

       // 未登录,直接返回房源信息
        if(!$token){
            $house->liked = false;
            return $house;
        }
       
        // 如果已登录用户,携带是否关注属性返回;

        $user = User::where('api_token',$token)->first();

        $house->liked = $this->liked($user->id,$request->id); 
        return $house;

    }

    
    // 获取房屋所有图片
    private function getImgArr($str){

        $imgArr = explode("&", $str);

        foreach($imgArr as $k=>$imgName){
            $imgArr[$k] =  config('app.upload').$imgName;
        }
        return $imgArr;

    }


    //图片字符串转数组
    private  function getCoverImg($str){
        $imgArr = explode("&", $str);
        return config('app.upload').'s_'.$imgArr[0]; // 默认第一张图片为封面图片;
    }
    
    
    // 房屋列表
    public function list(Request $request){

       //$houses = House::withTrashed()->paginate(5);
       $houses = House::where('title','like','%'.$request->words.'%')->orderBy("created_at","desc")->paginate($request->size);
        foreach($houses as $k=>$house){
            $houses[$k]["coverurl"]= $this->getCoverImg($house["imgs"]);
            unset($houses[$k]["imgs"]);
        }
        return $houses;

    } 
   
    // 上传图片
    public function upload(Request $request){
        
            //$file = $request->file;
        
            $path=base_path('public/upload/');    // 上传路径
            $file = $request->file('file');  //获取UploadFile实例
            $ext = $file->getClientOriginalExtension(); //扩展名
            $file_name = time().rand(0,999) . "." . $ext;    //重命名
            $res=$file->move($path, $file_name); //将上传文件移动至指定目录

            return $file_name;  
            
        // if($request->index == '0'){
        //     $this->imageResize($path,$file_name); 
        // }
        // return $file_name;
        
    }

    // 保存房源信息(小程序)

    public function store(Request $request){

        $token = $request->bearerToken();
        $cache = $this->get_token_value($token);

        $house = new House();
        $house->title  = $request->title;
        $house->des = $request->des;
        $house->imgs = $request->imgs;
        $house->tel = $request->tel;
        $house->name = $request->name;
        $house->state = 0;
        $house->uid = $cache->uid;
        
        $r=$house->save(); 
        
        if($r){
            return response()->json(["msg"=>"发布成功!!","status"=>200,'data'=>$house]);
        }else{
            return response()->json(["msg"=>"发布失败!!","status"=>3000,'data'=>$house]);
        }
        
    }


    // 保存信息
    public function save(Request $request){

        // 获取缓存信息
        $token = $request->bearerToken();
        $cache = $this->get_token_value($token);

        $house = new House();
        $house->title  = $request->title;

        if(strlen($house->imgs)>6){
            $house->imgs = implode("&", $request->imgs).'&'.$house->imgs;
        }else{
            $house->imgs = implode("&", $request->imgs);
        }

        $house->des = $request->des;
        $house->tel = $request->tel;
        $house->uid = $cache->uid;

        $r=$house->save();

        if($r){
            return response()->json(["msg"=>"发布成功!!","status"=>"201"]);
        }else{
            return response()->json(["msg"=>"发布失败!!","status"=>"3001"]);
        }
        
    }

    // 更新房源信息

    public function update(Request $request){

        // 获取缓存信息
        $token = $request->bearerToken();
        $cache = $this->get_token_value($token);

        $house = House::find($request->id);
        $house->title  = $request->title;
        $house->des = $request->des;
        $house->tel = $request->tel;
        $house->name = $request->name;
        
        $house->uid = $cache->uid;

        //$house->imgs = $house->imgs."&".$request->imgs;
       
        if(count($request->imgs)>=1){
           $house->imgs = $house->imgs.'&'.implode("&", $request->imgs);
        }

        $r=$house->save();

        if($r){
            return response()->json(["msg"=>"更新成功!!","status"=>"201"]);
        }else{
            return response()->json(["msg"=>"更新失败!!","status"=>"3001"]);
        }


    }


    // 我的发布
    public function my_house(){

       $houses = House::all();
       return $houses;

    }


    // 获取缓存
    private function get_token_value($token){

        $json_str = Cache::get($token);
        $res = json_decode($json_str,false);
        return $res;

    }


    // 生成缩略图;
    private function imageResize($path, $picname, $maxW=100, $maxH=100, $pre='s_')

    {

    //2.去除path路径右侧的 /，再加上
    $path = rtrim($path,'/').'/';

    //3.获取一张图片详细信息
    $info = getimagesize($path.$picname);

    //4.根据用户上传的图像的类型，来判断我们需要用哪一个函数生成画布(imagejpeg、imagepng、imagegif)
    switch($info[2]){
        case "1":   //gif
            $oldImg = imagecreatefromgif($path.$picname);
            break;

        case "2":   //jpg
            $oldImg = imagecreatefromjpeg($path.$picname);
            break;

        case "3":   //png
            $oldImg = imagecreatefrompng($path.$picname);
            break;
    }

    //5.获取原图的宽高
    $oldW = imagesx($oldImg);
    $oldH = imagesy($oldImg);

    //6.判断原图的宽高那个边比较长
    if($oldW > $oldH){

        //计算比例
        $b = $oldW / $maxW;

        //计算缩放后的新的宽度与高度
        $newW = $oldW / $b;
        $newH = $oldH / $b;
    }else{

        //计算比例
        $b = $oldH / $maxH;

        //计算缩放后的新的宽度与高度
        $newW = $oldW / $b;
        $newH = $oldH / $b;
    }

    //7.根据缩放后的宽度与高度，生成一个新的画布
    $newImg = imagecreatetruecolor($newW, $newH);

    //8.开始缩放
    imagecopyresampled($newImg, $oldImg, '0','0','0','0',$newW,$newH,$oldW,$oldH);

    //9.根据原图的类型，生成对应的图像
    switch($info[2]){
        case "1":
            imagegif($newImg, $path.$pre.$picname); //./Uplods/s_123.jpg
            break;

        case "2":
            imagejpeg($newImg, $path.$pre.$picname);
            break;

        case "3":
            imagepng($newImg, $path.$pre.$picname);
            break;
    }

    //10.释放资源
    imagedestroy($oldImg);
    imagedestroy($newImg);

   }


}
